package com.taotao.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.mapper.TbContentMapper;
import com.taotao.pojo.TbContent;
import com.taotao.pojo.TbContentExample;
import com.taotao.pojo.TbContentExample.Criteria;

@Service
public class ContentServiceImpl implements ContentService {

	@Autowired
	private TbContentMapper contentMapper;

	@Override
	public EUDataGridResult getContentList(long categoryId, int page, int rows) {
		// TODO Auto-generated method stub
		TbContentExample example = new TbContentExample();
		PageHelper.startPage(page, rows);
		Criteria criteria = example.createCriteria();
		criteria.andCategoryIdEqualTo(categoryId);
		List<TbContent> list = contentMapper.selectByExample(example);

		EUDataGridResult result = new EUDataGridResult();
		result.setRows(list);
		PageInfo<TbContent> pageInfo = new PageInfo<TbContent>(list);
		result.setTotal(pageInfo.getTotal());

		return result;
	}

	@Override
	public TaotaoResult saveContent(long categoryId, String title, String subTitle, String titleDesc, String url,
			String pic, String pic2, String content) {
		// TODO Auto-generated method stub
		TbContent con = new TbContent();
		con.setCategoryId(categoryId);
		con.setTitle(title);
		con.setSubTitle(subTitle);
		con.setTitleDesc(titleDesc);
		con.setUrl(url);
		con.setPic(pic);
		con.setPic2(pic2);
		con.setContent(content);
		con.setCreated(new Date());
		con.setUpdated(new Date());
		if (contentMapper.insert(con) > 0) {
			return TaotaoResult.ok(con);
		} else {
			return TaotaoResult.ok();
		}
	}

	@Override
	public TaotaoResult editContent(long categoryId, long id, String title, String subTitle, String titleDesc,
			String url, String pic, String pic2, String content) {
		// TODO Auto-generated method stub
		TbContent editCon = contentMapper.selectByPrimaryKey(id);
		editCon.setTitle(title);
		editCon.setSubTitle(subTitle);
		editCon.setTitleDesc(titleDesc);
		editCon.setUrl(url);
		editCon.setPic(pic);
		editCon.setPic2(pic2);
		editCon.setContent(content);
		editCon.setUpdated(new Date());
		if (contentMapper.updateByPrimaryKeyWithBLOBs(editCon) > 0) {
			return TaotaoResult.ok(editCon);
		} else {
			return TaotaoResult.ok();
		}
	}

	@Override
	public TaotaoResult deleteContent(long ids) {
		// TODO Auto-generated method stub
		Long categoryId = contentMapper.selectByPrimaryKey(ids).getCategoryId();
		contentMapper.deleteByPrimaryKey(ids);
		return TaotaoResult.ok(categoryId);
	}

}
